package com.dissertation.service.impl;

import com.dissertation.annotation.AdminAuth;
import com.dissertation.annotation.AdminOrTeacherAuth;
import com.dissertation.annotation.AllUserAuth;
import com.dissertation.model.Participant;
import com.dissertation.model.StudentParticipant;
import com.dissertation.model.TeacherParticipant;
import com.dissertation.model.auth.Role;
import com.dissertation.model.auth.User;
import com.dissertation.pojo.Message;
import com.dissertation.respository.ParticipantRepository;
import com.dissertation.respository.UserRepository;
import com.dissertation.service.ParticipantService;
import com.dissertation.utils.ExcelUtil;
import com.dissertation.utils.MD5Util;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

@Service
public class ParticipantImpl implements ParticipantService{

    @Autowired
    ParticipantRepository participantRepository;
    @Autowired
    MongoTemplate template;
    @Autowired
    UserRepository userRepository;

    @AllUserAuth
    @Override
    public String addStudent(StudentParticipant studentParticipant) {
        studentParticipant = participantRepository.save(studentParticipant);
        return studentParticipant.getId();
    }

    @AdminOrTeacherAuth
    @Override
    public String addTeacher(TeacherParticipant teacherParticipant) {
        teacherParticipant = participantRepository.save(teacherParticipant);
        return teacherParticipant.getId();
    }

    @AdminAuth
    @Override
    public Message searchStudentByName(String name, String schoolName) {
//        Class<?> clazz = Class.forName(com.dissertation.model.StudentParticipant);
        Pattern pattern = Pattern.compile("^.*" + name +".*$", Pattern.CASE_INSENSITIVE);
        Query query = Query.query(Criteria.where("uniqueName").regex(pattern).and( "deleted" ).is( false ).and("studentNumber").exists(true).and("schoolName").is(schoolName));
        List<StudentParticipant> studentParticipantList = template.find(query, StudentParticipant.class);
        return Message.createSuc( studentParticipantList );
    }

    @AdminAuth
    @Override
    public Message searchStudentNoName(String name, String schoolName) {
        Pattern pattern = Pattern.compile("^.*" + name +".*$", Pattern.CASE_INSENSITIVE);
        Query query = Query.query(Criteria.where("uniqueName").regex(pattern).and( "deleted" ).is( false ).and("studentNumber").exists(true).and("schoolName").ne(schoolName));
        List<StudentParticipant> studentParticipantList = template.find(query, StudentParticipant.class);
        return Message.createSuc( studentParticipantList );
    }

    @AdminAuth
    @Override
    public Integer importStudentParticipant(List<MultipartFile> files) {
        Integer  totalNum = 0;
        Integer num = 0;//总记录数
        Integer filenum = 0;//第几个文件
        for(MultipartFile file : files){
            filenum ++;
            List<Integer> finalnum = importSingleStudentParticipant(file, filenum, num);
            if(finalnum.get(0) == 0) {
                num += finalnum.get(1);
                continue;
            }
        }
        if(filenum == files.size()){
            totalNum = num;
        }
        return totalNum;
    }

    @AdminAuth
    @Override
    public Message searchTeacherByName(String name, String schoolName) {
        Pattern pattern = Pattern.compile("^.*" + name +".*$", Pattern.CASE_INSENSITIVE);
        Query query = Query.query(Criteria.where("uniqueName").regex(pattern).and( "deleted" ).is( false ).and("jobNumber").exists(true).and("schoolName").is(schoolName));
        List<TeacherParticipant> teacherParticipantList = template.find(query, TeacherParticipant.class);
        return Message.createSuc( teacherParticipantList );
    }

    @AdminAuth
    @Override
    public Message searchTeacherNoName(String name, String schoolName) {
        Pattern pattern = Pattern.compile("^.*" + name +".*$", Pattern.CASE_INSENSITIVE);
        Query query = Query.query(Criteria.where("uniqueName").regex(pattern).and( "deleted" ).is( false ).and("jobNumber").exists(true).and("schoolName").ne(schoolName));
        List<TeacherParticipant> teacherParticipantList = template.find(query, TeacherParticipant.class);
        return Message.createSuc( teacherParticipantList );
    }

    @AdminAuth
    @Override
    public Integer importTeacherParticipant(List<MultipartFile> files) {
        Integer  totalNum = 0;
        Integer num = 0;//总记录数
        Integer filenum = 0;//第几个文件
        for(MultipartFile file : files){
            filenum ++;
            List<Integer> finalnum = importSingleTeacherParticipant(file, filenum, num);
            if(finalnum.get(0) == 0) {
                num += finalnum.get(1);
                continue;
            }
        }
        if(filenum == files.size()){
            totalNum = num;
        }
        return totalNum;
    }


    @Override
    public Integer deleteParticipant(List<String> ids) {
        Integer num = 0;
        for(String id : ids){
            deleteSingleParticipant(id);
            num ++;
        }
        return num;
    }

    public void deleteSingleParticipant(String id){
        Participant participant = participantRepository.findOne(id);
        participant.setDeleted(true);
        participantRepository.save(participant);
    }

    public List<Integer> importSingleStudentParticipant(MultipartFile multipartFile, Integer filenum, Integer num){
        List<Integer> finalnum = new ArrayList<>();
        finalnum.add(0);  finalnum.add(0);
        Integer importnum = 0;
        Integer wrongnum = 1;
        Integer totalSavenum = num;
        List<StudentParticipant> studentParticipantList = new ArrayList<>();
        try {
            InputStream is = multipartFile.getInputStream();
            //根据版本选择创建Workbook的方式
            Workbook wb = null;
            //根据文件名判断文件是2003版本还是2007版本
            if (ExcelUtil.isExcel2007(multipartFile.getOriginalFilename())) {
                wb = new XSSFWorkbook(is);
            } else {
                wb = new HSSFWorkbook(is);
            }
            //readExcelValue

            //得到第一个shell
            Sheet sheet = wb.getSheetAt(0);
            //得到Excel的行数
            int totalRows = sheet.getPhysicalNumberOfRows();
            //总列数
            int totalCells = 0;
            if (totalRows >= 2 && sheet.getRow(1) != null) {
                totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
            }
            //循环Excel行数,从第二行开始。标题不入库
            for (int r = 1; r < totalRows; r++) {
                Row row = sheet.getRow(r);
                if (row == null) continue;
                StudentParticipant studentParticipant = new StudentParticipant();
                Cell cell;
                String[] shuzu;
                int nullnum = 0;
                int notnullnum = 0;
                //姓名
                cell = row.getCell(0);
                studentParticipant.setUniqueName(getCellValue(cell));
                //学院
                cell = row.getCell(1);
                studentParticipant.setSchoolName(getCellValue(cell));
                //专业
                cell = row.getCell(2);
                studentParticipant.setMajor(getCellValue(cell));
                //电话
                cell = row.getCell(3);
                studentParticipant.setPhone(getCellValue(cell));
                //邮箱
                cell = row.getCell(4);
                studentParticipant.setEmail(getCellValue(cell));
                //用户账号 可以为null
                cell = row.getCell(5);
                studentParticipant.setUserId(getCellValue(cell));
                //学号
                cell = row.getCell(6);
                studentParticipant.setStudentNumber(getCellValue(cell));
                //年级
                cell = row.getCell(7);
                studentParticipant.setGrade(getCellValue(cell));

                participantRepository.save(studentParticipant);
                studentParticipantList.add(studentParticipant);
                if (studentParticipant != null) {
                    importnum++;
                    wrongnum = importnum + 1;
                } else break;
            }

        }catch (Exception e) {
            e.printStackTrace();
            totalSavenum += importnum;
            throw new RuntimeException("第" + filenum + "张表， " + "第" + wrongnum + "条数据出现异常，请检查!且该行数据之前的" + totalSavenum + "条数据插入成功");
        }
        if (importnum == studentParticipantList.size()) {
            finalnum.add(0);
            finalnum.set(1, importnum);
        }
        return finalnum;

    }

    public List<Integer> importSingleTeacherParticipant(MultipartFile multipartFile, Integer filenum, Integer num){
        List<Integer> finalnum = new ArrayList<>();
        finalnum.add(0);  finalnum.add(0);
        Integer importnum = 0;
        Integer wrongnum = 1;
        Integer totalSavenum = num;
        List<TeacherParticipant> teacherParticipantList = new ArrayList<>();

        try {
            InputStream is = multipartFile.getInputStream();
            //根据版本选择创建Workbook的方式
            Workbook wb = null;
            //根据文件名判断文件是2003版本还是2007版本
            if (ExcelUtil.isExcel2007(multipartFile.getOriginalFilename())) {
                wb = new XSSFWorkbook(is);
            } else {
                wb = new HSSFWorkbook(is);
            }
            //readExcelValue

            //得到第一个shell
            Sheet sheet = wb.getSheetAt(0);
            //得到Excel的行数
            int totalRows = sheet.getPhysicalNumberOfRows();
            //总列数
            int totalCells = 0;
            if (totalRows >= 2 && sheet.getRow(1) != null) {
                totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
            }
            //循环Excel行数,从第二行开始。标题不入库
            for (int r = 1; r < totalRows; r++) {
                Row row = sheet.getRow(r);
                if (row == null) continue;
                TeacherParticipant teacherParticipant = new TeacherParticipant();
                User user = new User();
                Cell cell;
                //姓名
                cell = row.getCell(0);
                teacherParticipant.setUniqueName(getCellValue(cell));
                user.setUniqueName(getCellValue(cell));
                //学院
                cell = row.getCell(1);
                teacherParticipant.setSchoolName(getCellValue(cell));
                //专业
                cell = row.getCell(2);
                teacherParticipant.setMajor(getCellValue(cell));
                //电话
                cell = row.getCell(3);
                teacherParticipant.setPhone(getCellValue(cell));
                //邮箱
                cell = row.getCell(4);
                teacherParticipant.setEmail(getCellValue(cell));
                //用户账号 可以为null
                cell = row.getCell(5);
                teacherParticipant.setUserId(getCellValue(cell));
                //工号
                cell = row.getCell(6);
                teacherParticipant.setJobNumber(getCellValue(cell));
                user.setPassword(MD5Util.toMD5(getCellValue(cell)));
                //职称
                cell = row.getCell(7);
                teacherParticipant.setJobName(getCellValue(cell));
                //职位
                cell = row.getCell(8);
                teacherParticipant.setJob(getCellValue(cell));
                //财务账号
                cell = row.getCell(9);
                teacherParticipant.setFinancialAcount(getCellValue(cell));

                participantRepository.save(teacherParticipant);
                teacherParticipantList.add(teacherParticipant);

                user.addRoles(Role.TEACHER);
                user.setDeleted(false);
                user.setSecurity(false);
                userRepository.save(user);
                if (teacherParticipant != null) {
                    importnum++;
                    wrongnum = importnum + 1;
                } else break;
            }

        }catch (Exception e){
            e.printStackTrace();
            totalSavenum += importnum;
            throw new RuntimeException("第" + filenum + "张表， " + "第" + wrongnum + "条数据出现异常，请检查!且该行数据之前的" + totalSavenum + "条数据插入成功");
        }
        if (importnum == teacherParticipantList.size()) {
            finalnum.add(0);
            finalnum.set(1, importnum);
        }
        return finalnum;
    }

    /**
     * 从cell获得值
     * */
    public  String getCellValue(Cell cell) {
        String value = "";
        if (cell != null) {
            cell.setCellType(Cell.CELL_TYPE_STRING);
            value = cell.getStringCellValue();
        }
        return value;
    }

    @Override
    public List<Participant> searchAllParticipant() {
        return participantRepository.findAllByDeletedIsFalse();
    }

    @Override
    public List<Participant> searchByName(String name) {
        Pattern pattern = Pattern.compile("^.*" + name +".*$", Pattern.CASE_INSENSITIVE);
        Query query = Query.query(Criteria.where("uniqueName").regex(pattern).and( "deleted" ).is( false ));
        return template.find(query, Participant.class);
    }
}
